<?php

require_once "mysql.php";

// Get the URL arguments.
$player_id = mysql_real_escape_string($_GET["player_id"]);
$name = mysql_real_escape_string($_GET["name"]);
$x = mysql_real_escape_string($_GET["x"]);
$y = mysql_real_escape_string($_GET["y"]);
$z = mysql_real_escape_string($_GET["z"]);

// Register the player's new position, if appropriate.
if (strlen($player_id) > 0 &&
    strlen($x) > 0 &&
    strlen($y) > 0 &&
    strlen($z) > 0) {
  mysql_query("DELETE FROM players WHERE player_id = $player_id");
  mysql_query("INSERT INTO players (player_id,name,timestamp,x,y,z) " .
	      "VALUES ($player_id,'$name',CURRENT_TIMESTAMP,$x,$y,$z)");
}

// Delete any players that have not updated their positions recently enough.
mysql_query("DELETE FROM players " .
	    "WHERE timestamp < CURRENT_TIMESTAMP - INTERVAL 5 MINUTE");

// Get the list of players and output it in JSON format.
$query = "SELECT * FROM players";
$results = mysql_query($query);
$first_result = True;
echo "[";
while ($row = mysql_fetch_assoc($results)) {
  $name = $row["name"];
  $x = $row["x"];
  $y = $row["y"];
  $z = $row["z"];
  if ($first_result) {
    $first_result = False;
  } else {
    echo ",";
  }
  echo "{\"name\":\"$name\",\"x\":$x,\"y\":$y,\"z\":$z}";
}
echo "]";

?>
